package com.platform.license;

import org.apache.commons.codec.digest.DigestUtils;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.ComputerSystem;
import oshi.hardware.HardwareAbstractionLayer;

/**
 * @author liujizheng
 * @version 1.0
 * @ClassName MachineUtils
 * @Description 机器硬件工具类，使用oshi获取机器唯一编号
 * @date 2022/1/10 18:16
 */
public class MachineUtils {
    /**
     * 生成java编码
     *
     * @return
     */
    public static String generate() {
        // 获取主机信息
        SystemInfo systemInfo = new SystemInfo();

        HardwareAbstractionLayer hal = systemInfo.getHardware();
        ComputerSystem computerSystem = hal.getComputerSystem();
        // 序列号信息
        String sn = computerSystem.getSerialNumber();

        CentralProcessor processor = hal.getProcessor();
        // CPU
        String processId = processor.getProcessorID();
        String str = String.format("{sn: %s, process: %s}", sn, processId);
        String md5 = DigestUtils.md5Hex(str).toUpperCase();

        // 换序
        String result = swap(md5);

        return reverse(result);
    }

    private static String reverse(String str) {
        StringBuilder builder = new StringBuilder();
        int length = str.length();
        for (int i = length - 1; i > 0; i--) {
            builder.append(str.charAt(i));
        }
        return builder.toString();
    }

    private static String swap(String str) {
        StringBuilder odd = new StringBuilder();
        StringBuilder even = new StringBuilder();

        int length = str.length();
        for (int i = 0; i < length; i++) {
            if (i % 2 == 0) {
                even.append(str.charAt(i));
            } else {
                odd.append(str.charAt(i));
            }
        }

        return even.toString() + odd.toString();
    }
}
